package com.starbaba.messageManager.view;

import com.base.common.database.BaseDao;
import com.base.common.log.LogService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.messageManager.model.PhoneMessageRecord;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.spreadChannelManager.model.ProductCodeModel;
import com.starbaba.stat.model.QueryListVO;
import com.starbaba.tools.sms.SendMessageUtil;
import com.starbaba.util.ExcelOperateUtil;
import com.starbaba.util.QueryListUtil;
import com.tuanzi.server.loan_base.util.PhoneNumNideUtil;
import org.apache.struts2.ServletActionContext;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Yukinomiu
 * @version 1.0
 */
public class ShortMessageAction extends ActionSupport implements ModelDriven {

    private static final long serialVersionUID = -1843820729227175266L;

    private static final String LOGGER_NAME = ShortMessageAction.class.getName();

    private Map<String, Object> responseMap = new HashMap<>(3, .75F);

    public Map<String, Object> getResponseMap() {
        return responseMap;
    }

    private QueryListUtil.DataTableResponseInfo responseInfo;

    public QueryListUtil.DataTableResponseInfo getResponseInfo() {
        return responseInfo;
    }

    private InputStream inputStream;

    private String fileName;

    public InputStream getInputStream() {
        return inputStream;
    }

    public String getFileName() {
        return fileName;
    }

    private String savePath;

    public String getSavePath() {
        return savePath;
    }

    public ShortMessageAction setSavePath(String savePath) {
        this.savePath = savePath;
        return this;
    }

    private File upload;

    public File getUpload() {
        return upload;
    }

    public ShortMessageAction setUpload(File upload) {
        this.upload = upload;
        return this;
    }

    @Override
    public Object getModel() {
        return null;
    }

    public String showListPage() {
        return SUCCESS;
    }

    public String getRecord() {
        Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
        QueryListUtil.dropEmptyParams(params);

        Map<String, Object> queryParams = new HashMap<>();
        Integer echo;
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 查询参数
            if (params.get("startDate") != null) {
                queryParams.put("startDate", sdf.parse((String) params.get("startDate")));
            }
            if (params.get("endDate") != null) {
                Date endDate = sdf.parse((String) params.get("endDate"));
                c.setTime(endDate);
                c.set(Calendar.HOUR_OF_DAY, 23);
                c.set(Calendar.MINUTE, 59);
                c.set(Calendar.SECOND, 59);
                c.set(Calendar.MILLISECOND, 0);
                queryParams.put("endDate", c.getTime());
            }
            if (params.get("phone") != null) {
                queryParams.put("phone", params.get("phone"));
            }
            if (params.get("product") != null) {
                queryParams.put("product", params.get("product"));
            }
            if (params.get("remark") != null) {
            	queryParams.put("remark", params.get("remark"));
            }

            // 表单控件参数
            QueryListUtil.DataTableRequestInfo info = QueryListUtil.getDataTableRequestInfo(params);

            echo = info.getEcho();

            Integer start = info.getStart();
            Integer limit = info.getLimit();

            queryParams.put("start", start);
            queryParams.put("limit", limit);
        } catch (Exception e) {
            LogService.info(LOGGER_NAME + ": 请求解析异常: " + e.getMessage());
            return ERROR;
        }

        try {
//            BaseDao baseDao = new BaseDao(Constant.COMPANY_DB_POOL);
            BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);

            List<Object> whereParams = new LinkedList<>();
            StringBuilder fromSQL = new StringBuilder(" from phone_message_record r where 1 = 1 ");
            if (queryParams.get("startDate") != null) {
                fromSQL.append("and r.ctime >= ? ");
                whereParams.add(queryParams.get("startDate"));
            }
            if (queryParams.get("endDate") != null) {
                fromSQL.append("and r.ctime <= ? ");
                whereParams.add(queryParams.get("endDate"));
            }
            if (queryParams.get("phone") != null) {
                fromSQL.append("and r.phonenum = ? ");
                whereParams.add(queryParams.get("phone"));
            }
            
            if (queryParams.get("product") != null) {
                fromSQL.append("and r.product_id = ? ");
                whereParams.add(queryParams.get("product"));
            }
            
            if (queryParams.get("remark") != null) {
            	fromSQL.append("and r.memo like concat('"+queryParams.get("remark")+"'," + "'%'" + ")");
            	//fromSQL.append("and r.memo like '"+queryParams.get("remark")+"%' ");
            }


            String countSQL = "select count(*)" + fromSQL.toString();
            int count = baseDao.getInt(countSQL, whereParams);

            QueryListVO vo;
            if (count == 0) {
                vo = new QueryListVO(count, null);
            }
            else {
                fromSQL.append("order by r.ctime desc ");
                fromSQL.append("limit ?, ?");
                whereParams.add(queryParams.get("start"));
                whereParams.add(queryParams.get("limit"));
                String selectSQL = "select *" + fromSQL.toString();
                List<PhoneMessageRecord> list = baseDao.list(selectSQL, PhoneMessageRecord.class, whereParams);
                //将mobnum中间4为转为*
                for (int i = 0; i <list.size() ; i++) {
                    PhoneMessageRecord phoneMessageRecord = list.get(i);
                    phoneMessageRecord.setPhoneNum(PhoneNumNideUtil.hideNum(phoneMessageRecord.getPhoneNum()));
                    list.set(i,phoneMessageRecord);
                }

                vo = new QueryListVO(count, list);
            }

            responseInfo = QueryListUtil.getDataTableResponseInfo(echo, vo.getTotalCount(), vo.getList());
        } catch (Exception e) {
            LogService.error(LOGGER_NAME + ": 查询数据库异常: " + e.getMessage());
            return ERROR;
        }
        return SUCCESS;
    }

    public String exportRecord() {
        Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
        QueryListUtil.dropEmptyParams(params);

        Map<String, Object> queryParams = new HashMap<>();
        Calendar c = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 查询参数
            if (params.get("startDate") != null) {
                queryParams.put("startDate", sdf.parse((String) params.get("startDate")));
            }
            if (params.get("endDate") != null) {
                Date endDate = sdf.parse((String) params.get("endDate"));
                c.setTime(endDate);
                c.set(Calendar.HOUR_OF_DAY, 23);
                c.set(Calendar.MINUTE, 59);
                c.set(Calendar.SECOND, 59);
                c.set(Calendar.MILLISECOND, 0);
                queryParams.put("endDate", c.getTime());
            }
            if (params.get("phone") != null) {
                queryParams.put("phone", params.get("phone"));
            }
            if (params.get("product") != null) {
                queryParams.put("product", params.get("product"));
            }
            if (params.get("remark") != null) {
            	queryParams.put("remark", params.get("remark"));
            }
        } catch (Exception e) {
            LogService.info(LOGGER_NAME + ": 请求解析异常: " + e.getMessage());
            return ERROR;
        }

        try {
            BaseDao baseDao = new BaseDao(Constant.COMPANY_DB_POOL);

            List<Object> whereParams = new LinkedList<>();
            StringBuilder fromSQL = new StringBuilder(" from phone_message_record r where 1 = 1 ");
            if (queryParams.get("startDate") != null) {
                fromSQL.append("and r.ctime >= ? ");
                whereParams.add(queryParams.get("startDate"));
            }
            if (queryParams.get("endDate") != null) {
                fromSQL.append("and r.ctime <= ? ");
                whereParams.add(queryParams.get("endDate"));
            }
            if (queryParams.get("phone") != null) {
                fromSQL.append("and r.phonenum = ? ");
                whereParams.add(queryParams.get("phone"));
            }
            if (queryParams.get("product") != null) {
                fromSQL.append("and r.product_id = ? ");
                whereParams.add(queryParams.get("product"));
            }
            if (queryParams.get("remark") != null) {
            	fromSQL.append("and r.memo like concat('"+queryParams.get("remark")+"'," + "'%'" + ")");
            	//fromSQL.append("and r.memo like '"+queryParams.get("remark")+"%' ");
            }

            fromSQL.append("order by r.ctime desc ");
            String selectSQL = "select *" + fromSQL.toString();
            List<PhoneMessageRecord> list = baseDao.list(selectSQL, PhoneMessageRecord.class, whereParams);
            	
            StringBuilder sb = new StringBuilder("发送时间,产品,渠道,手机号码,短信内容,提交状态").append("\r\n");
            for (PhoneMessageRecord r : list) {
                sb.append(r.getCtime().toString()).append(",");
                sb.append(convertProduct(r.getProductId())).append(",");
                sb.append(r.getMemo()).append(",");
                sb.append("'").append(r.getPhoneNum()).append(",");
                sb.append(r.getContent());
                sb.append(r.getStatus() != null && r.getStatus() == 1 ? "成功" : "失败");
                sb.append("\r\n");
            }

            inputStream = new ByteArrayInputStream(sb.toString().getBytes("GBK"));
            fileName = "short_message_export_" + System.currentTimeMillis() + ".csv";
        } catch (Exception e) {
            LogService.error(LOGGER_NAME + ": 查询数据库异常: " + e.getMessage());
            return ERROR;
        }
        return SUCCESS;
    }

    public void uploadSmsBatch() throws IOException {
        File file = upload;
        if (file.exists()) {
            String fileName = file.getAbsolutePath();
            fileName = fileName.replace(".tmp", ".xls");
            file.renameTo(new File(fileName));
            file = new File(fileName);
        }
        else {
            sendPlainTest("上传失败: 文件不存在");
        }

        int totalCount = 0;
        int successCount = 0;
        try {
            String[][] result = ExcelOperateUtil.getData(file, 0, "yyyy-MM-dd", "#");
            totalCount = result.length - 1;
            for (int i = 1, l = result.length; i < l; ++i) {
                String[] r = result[i];
                String phone = r[0];
                String content = r[1];
                String memo = r[2];
                String productStr = r[3];
                int product;

                try {
                    product = Integer.valueOf(productStr);
                } catch (Exception e) {
                    LogService.error("批量发送短信异常, 渠道不为数字, 手机号码: " + phone + ", 短信内容: " + content + ", 渠道: " + memo + ", 产品ID: " + productStr);
                    continue;
                }

                // 发送短信
                try {
                    sendSms(phone, content, memo, product);
                    successCount++;
                } catch (Exception e) {
                    LogService.error("批量发送短信异常: " + e.getMessage());
                }
            }
        } catch (Exception e) {
            sendPlainTest("上传失败, 服务器错误: " + e.getMessage());
        }

        sendPlainTest("上传成功, 短信总数: " + totalCount + ", 实际发送数: " + successCount);
    }
    
    private static String convertProduct(Integer product) {
        if (product == null) {
        	return "";
        }
        
        try {
        	BaseDao dao = new BaseDao("tt1");
        	String codeSql = "select * from comm_product_prdid where prdid = ? limit 1";
        	ProductCodeModel productCodeModel = dao.get(codeSql, ProductCodeModel.class, product);
        	if (productCodeModel != null) {
				return productCodeModel.getName();
			}
		} catch (Exception e) {
		}
        
        return product.toString();
    }

    private void sendPlainTest(String message) throws IOException {
        ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
        PrintWriter out = ServletActionContext.getResponse().getWriter();
        out.print(message);
        out.flush();
        out.close();
    }

    private static boolean sendSms(String phone, String content, String memo, int product) {
        return SendMessageUtil.sendMessage(phone, content, memo, 1, product, 0);
    }
}
